package com.xiaoma.beanpostfactory;

import java.util.Map;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactory;

/**
 * <p>Title: RoutingBeanProxyFactory </p>
 * <p>Description：描述 </p>
 * <p>Package:com.xiaoma.beanpostfactory </p>
 * Copyright: Copyright(c) 2020 Travelsky All Rights Reserved Company: Travelsky Software: AIC Date: 2021/1/29 13:09
 *
 * @author maj
 * @version 1.0.0
 */
public class RoutingBeanProxyFactory {

  private final static String DEFAULT_BEAN_NAME = "helloServiceImpl1";

  public static Object createProxy(String name, Class type, Map<String, Object> candidates) {
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setInterfaces(type);
    proxyFactory.addAdvice(new VersionRoutingMethodInterceptor(name, candidates));
    return proxyFactory.getProxy();
  }

  static class VersionRoutingMethodInterceptor implements MethodInterceptor {
    private Object targetObject;

    public VersionRoutingMethodInterceptor(String name, Map<String, Object> beans) {
      this.targetObject = beans.get(name);
      if (this.targetObject == null) {
        this.targetObject = beans.get(DEFAULT_BEAN_NAME);
      }
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
      return invocation.getMethod().invoke(this.targetObject, invocation.getArguments());
    }
  }

}
